<template>
  <div class="app-container">
    <div class="bgWhite radius8  pt20 flex col-top row-between pr20">
      <el-form class="pl20 2" :model="queryParams" ref="queryForm" :inline="true"
        v-show="showSearch" label-width="100px">
          <el-form-item label="手机号" prop="phoneNumber">
            <el-input
				size="large"
                v-model="queryParams.phoneNumber"
                placeholder="搜索手机号"
                clearable
                @keyup.enter.native="handleQuery"
				style="width: 200px;"
            />
          </el-form-item>
          <el-form-item label="商机来源" prop="opportunitySource">
            <el-select
				size="large"
                v-model="queryParams.opportunitySource"
                placeholder="商机来源"
                clearable
                style="width: 200px">
              <el-option
                  v-for="dict in bus_source"
                  :key="dict.value"
                  :label="dict.label"
                  :value="dict.value"/>
            </el-select>
          </el-form-item>
      </el-form>
	  <div class="flex col-center">
		  <el-button class="searchBtn" type="defaultBtn" @click="handleQuery">搜索</el-button>
		  <el-button class="searchBtn" icon="Refresh" @click="resetQuery">重置</el-button>
	  </div>
    </div>
    <div class="bgWhite radius8 p20 mt25">
      <div class="flex col-center row-between mb20">
        <span class="fb fs16">部门商机列表</span>
        <div>
          <el-button type="operate" :disabled="multiple" @click="deptReceiveFormSub" v-hasPermi="['opportunity:deptReceive']">领取商机</el-button>
          <el-button type="operate" :disabled="multiple" @click="allocationFormSub" v-hasPermi="['opportunity:deptAllocation']">分配商机</el-button>
        </div>
      </div>


    <el-table v-loading="loading" :data="opportunityList"
	:header-row-style="{background:'#FAFAFA',color:'#0C1019',height:'54px'}"
	:cell-style="{height:'54px'}"
	@selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center"/>
      <el-table-column label="客户名称" align="center" prop="customerName"/>
      <el-table-column label="商机来源" align="center" prop="opportunitySource">
        <template #default="scope">
          <dict-tag :options="bus_source" :value="scope.row.opportunitySource"/>
        </template>
      </el-table-column>
      <el-table-column label="手机号" align="center" prop="phoneNumber"/>
      <el-table-column label="归属部门" align="center" prop="departName"/>
      <el-table-column label="归属小组" align="center" prop="teamName"/>
      <el-table-column label="归属业务经理" align="center" prop="businessManagerName"/>


      <el-table-column label="添加时间" align="center" prop="createTime"/>

      <el-table-column fixed="right" label="操作" align="center"  width="300px" class-name="small-padding fixed-width">
        <template #default="scope">
          <el-button
              link class="linkBtnColor" type="primary"
              @click="deptReceiveFormSub(scope.row)"
              v-hasPermi="['opportunity:deptReceive']"
          >领取商机
          </el-button>
          <el-button
              link class="linkBtnColor" type="primary"
              @click="allocationFormSub(scope.row)"
              v-hasPermi="['opportunity:deptAllocation']"
          >分配商机
          </el-button>
          <el-button
              link class="linkBtnColor" type="primary"
              @click="detailsOpenFun(scope.row)"
              v-hasPermi="['opportunity:getDeptDetails']"
          >查看详情
          </el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination
        v-show="total>0"
        :total="total"
        v-model:page="queryParams.pageNum"
        v-model:limit="queryParams.pageSize"
        @pagination="getList"
    />
    </div>
    <!--    分配弹出框-->
    <el-dialog :title="title" center v-model="allocationFormOpen" width="385px" append-to-body>
      <el-form ref="refAllocationForm" :model="allocationForm" :rules="allocationFormRules" label-width="80px">
        <el-form-item label="接收小组:" prop="deptId">
          <el-tree-select
              v-model="allocationForm.teamId"
              :data="deptOptions"
              :props="{ value: 'id', label: 'label', children: 'children' }"
              value-key="id"
              placeholder="请选择归属小组"
              check-strictly
          />
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer text-right mt30">
		  <el-button class="cancelSubBtn" @click="allocationFormOpen = false">取 消</el-button>
		  <el-button type="primary" @click="allocationSubmit" class="mainSubBtn">确 定</el-button>
      </div>
    </el-dialog>
    <!--    领取弹出框-->
    <el-dialog :title="title" center v-model="deptReceiveFormOpen" width="385px" append-to-body>
      <el-form ref="refdeptReceiveForm" :model="deptReceiveForm" :rules="deptReceiveFormRules" label-width="80px">
        <el-form-item label="接收小组:" prop="deptId">
          <el-tree-select
              v-model="deptReceiveForm.teamId"
              :data="deptOptions"
              :props="{ value: 'id', label: 'label', children: 'children' }"
              value-key="id"
              placeholder="请选择归属小组"
              check-strictly
          />
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer text-right mt30">
		  <el-button class="cancelSubBtn" @click="deptReceiveFormOpen = false">取 消</el-button>
		  <el-button type="primary" @click="deptReceiveSubmit" class="mainSubBtn">确 定</el-button>
      </div>
    </el-dialog>
    <!--    商机详情-->
    <el-dialog :title="title" center v-model="detailsOpen" width="700px" append-to-body>
      <el-descriptions title="" :column="2" border>
        <el-descriptions-item label="商机来源：">{{ getDictLabel(bus_source, detailsData.opportunitySource) }}
        </el-descriptions-item>
        <el-descriptions-item label="微信号码：">{{ detailsData.wxAccount }}</el-descriptions-item>
        <el-descriptions-item label="客户姓名：">{{ detailsData.customerName }}</el-descriptions-item>
        <el-descriptions-item label="手机号码：">{{ detailsData.phoneNumber }}</el-descriptions-item>
        <el-descriptions-item label="客户地址：">{{ detailsData.customerAddress }}</el-descriptions-item>
        <el-descriptions-item label="客户作物：">{{ detailsData.cropNames }}</el-descriptions-item>
        <el-descriptions-item label="客户需求：">{{ detailsData.customerNeed }}</el-descriptions-item>
        <el-descriptions-item label="添加时间：">{{ detailsData.createTime }}</el-descriptions-item>
        <el-descriptions-item label="客户靶标：">{{ getDictLabel(bus_target, detailsData.customerTarget) }}
        </el-descriptions-item>
        <el-descriptions-item label="归属部门：">{{ detailsData.departName }}</el-descriptions-item>
        <el-descriptions-item label="归属小组：">{{ detailsData.teamName }}</el-descriptions-item>
        <el-descriptions-item label="归属业务经理：">{{ detailsData.businessManagerName }}</el-descriptions-item>
      </el-descriptions>
    </el-dialog>
  </div>
</template>

<script setup name="OpportUnityDept">
import {
  getOpportunityInfo,
  listOpportunity, deptAllocation, deptReceive, deptTreeSelect
} from "@/api/business/deptOpportunity.js";

const {proxy} = getCurrentInstance();
const {
  bus_source,
  bus_channel,
  honorific,
  bus_target,
  bus_other_tag
} = proxy.useDict("bus_source", "bus_channel", "honorific", "bus_target", "bus_other_tag");

const opportunityList = ref([]);
const open = ref(false);
const loading = ref(true);
const showSearch = ref(true);
const ids = ref([]);
const single = ref(true);
const multiple = ref(true);
const total = ref(0);
const title = ref("");
const deptOptions = ref(undefined);
const data = reactive({
  form: {},
  queryParams: {
    pageNum: 1,
    pageSize: 10,
    opportunitySource: null,
    phoneNumber: null,
    opportunityDataType: 1,
  },
  rules: {
    postName: [{required: true, message: "", trigger: "blur"}],
  }
});
const {queryParams, form, rules} = toRefs(data);

/** 查询商机列表 */
function getList() {
  loading.value = true;
  listOpportunity(queryParams.value).then(response => {
    opportunityList.value = response.rows;
    total.value = response.total;
    loading.value = false;
  });
}

/** 搜索按钮操作 */
function handleQuery() {
  queryParams.value.pageNum = 1;
  getList();
}

/** 重置按钮操作 */
function resetQuery() {
  proxy.resetForm("queryForm");
  handleQuery();
}

// 多选框选中数据
function handleSelectionChange(selection) {
  ids.value = selection.map(item => item.id)
  single.value = selection.length !== 1
  multiple.value = !selection.length
}


//手动分配部门
const allocationFormOpen = ref(false);
const dataAllocationFormData = reactive({
  allocationForm: {},
  allocationFormParams: {
    ids: 0,
    teamId: 0,
  },
  allocationFormRules: {
    postName: [{required: true, message: "", trigger: "blur"}],
  }
});
const {allocationForm, allocationFormRules} = toRefs(dataAllocationFormData);

/** 分配 */
function allocationSubmit() {
  deptAllocation(allocationForm.value).then(response => {
    allocationFormOpen.value = false;
    getList();
  });
}

/** 点击分配 */
function allocationFormSub(row) {
  let id = row.id || ids.value
  allocationFormOpen.value = true;
  title.value = "分配商机";
  if (!Array.isArray(id)) {
    // 如果id不是数组，将其转换为数组，并且只有一个元素
    id = [id];
  }
  allocationForm.value.ids = id.join(',');
}


//手动领取
const deptReceiveFormOpen = ref(false);
const deptReceiveFormData = reactive({
  deptReceiveForm: {},
  deptReceiveFormParams: {
    ids: 0,
    teamId: 0,
  },
  deptReceiveFormRules: {
    postName: [{required: true, message: "", trigger: "blur"}],
  }
});
const {deptReceiveForm, deptReceiveFormRules} = toRefs(deptReceiveFormData);

/** 点击领取 */
function deptReceiveFormSub(row) {
  let id = row.id || ids.value
  deptReceiveFormOpen.value = true;
  title.value = "领取商机";
  if (!Array.isArray(id)) {
    // 如果id不是数组，将其转换为数组，并且只有一个元素
    id = [id];
  }
  deptReceiveForm.value.ids = id.join(',');
}

/** 领取 */
function deptReceiveSubmit() {
  deptReceive(deptReceiveForm.value).then(response => {
    deptReceiveFormOpen.value = false;
    getList();
  });
}


/*获取详情*/
const detailsOpen = ref(false);
const detailsData = ref({
  id: null,
  opportunitySource: null,
  wxAccount: null,
  customerName: null,
  phoneNumber: null,
  localArea: null,
  cropNames: null,
  customerNeed: null,
  createTime: null,
  customerTarget: null,
  departName: null,
  teamName: null,
  businessManagerName: null

});

/** 点击详情按钮 */
function detailsOpenFun(row) {
  const id = row.id || ids.value
  getOpportunityInfo(id).then(response => {
    detailsData.value = response.data;
    detailsOpen.value = true;
    title.value = "商机详情";
  });
};

// 根据字典数据和值获取对应的标签（汉字）
function getDictLabel(dict, value) {
  if(value){
  	let arr =  value.split(',')
  	let keyString = ''
  	for(let j in dict){
  		for(let key in arr){
  			if(arr[key] == dict[j].value){
  				keyString+=dict[j].label+','
  			}
  		}
  	}
  	return keyString.slice(0,-1)
  }
};

/**
 * 获取部门数据
 */
function getDeptTree() {
  deptTreeSelect().then(response => {
    deptOptions.value = response.data;
  });
};
getList();
getDeptTree();
</script>
<style>
.my-label {
  background: #E1F3D8;
}

.my-content {
  background: #FDE2E2;
}
</style>
